package com.hcb.tonguetiphealth.widget.drinksbook;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextPaint;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;

import com.hcb.tonguetiphealth.adapter.DrinksBookDrinkInfoExpandableListAdapter;
import com.hcb.tonguetiphealth.adapter.GeneralPageAdapter;
import com.hcb.tonguetiphealth.global.Global;
import com.hcb.tonguetiphealth.manager.JSONManager;
import com.hcb.tonguetiphealth.model.Drinks;
import com.hcb.tonguetiphealth.model.DrinksBookDrinkInfoGroup;
import com.hcb.tonguetiphealth.util.HttpUtils;
import com.hcb.tonguetiphealth.util.MessageWhat;
import com.hcb.tonguetiphealth.util.StringUtils;
import com.hcb.tonguetiphealth.view.R;
import com.hcb.tonguetiphealth.widget.CommentWidget;
import com.hcb.tonguetiphealth.widget.GeneralWidget;
import com.hcb.tonguetiphealth.widget.recommendhealth.RecommendHealthWidget;

public class DrinksBookDrinkInfoWidget extends GeneralWidget implements OnClickListener {
	private static final String TAG = "DrinksBookWidget";
	private String url = Global.URL + Global.servlet_wineInfo;
	private Activity ctx;
	private LayoutInflater inflater;
	private Handler mHandler;
	private Drinks crrentDrinks;
	private List<Drinks> drinksList;
	private ImageView iv, iv1, iv2, iv3, iv4, iv5, iv6;
	
	private TextView name, priceTip, priceMarket, tel;
	private RatingBar ratingBar;
	private LinearLayout bt_back, bt_cart, bt_add, bt_share;
	private EditText bookNum;
	
	private ExpandableListView expandableListView;
	private List<DrinksBookDrinkInfoGroup> groupList;
	private DrinksBookDrinkInfoGroup group;
	private List<String> childList;
	private DrinksBookDrinkInfoExpandableListAdapter eAdapter;
	private int crrentPageId = 0;
	
	private ViewPager viewPager;
	private List<View> pageViews;
	private View view;
	private GeneralPageAdapter pageAdapter;
	private String from;
	
	public DrinksBookDrinkInfoWidget(Context context) {
		super(context);
		ctx = (Activity)context;
		crrentDrinks = (Drinks)ctx.getIntent().getSerializableExtra("drinks");
		from = ctx.getIntent().getStringExtra("from");
		ctx.getIntent().putExtra("from", "");
		drinksList = Global.drinksList;
				
		inflater = ctx.getLayoutInflater();
		inflate(context, R.layout.drinks_book_drinks_info, this); 
		
		iv = (ImageView)findViewById(R.id.drinks_book_drink_info_img);
		name = (TextView)findViewById(R.id.drinks_book_drink_info_name_textview);
		TextPaint tp = name.getPaint(); 
		tp.setFakeBoldText(true); 
		priceTip = (TextView)findViewById(R.id.drinks_book_drink_info_price_textview);
		priceMarket = (TextView)findViewById(R.id.drinks_book_drink_info_price_market_textview);
		tel = (TextView)findViewById(R.id.drinks_book_drink_info_hpone_textview); 
		ratingBar = (RatingBar)findViewById(R.id.drinks_book_drink_info_ratings_ratingbar);
		
		bt_back = (LinearLayout)findViewById(R.id.drink_book_drink_info_back_button);
		bt_cart = (LinearLayout)findViewById(R.id.drink_book_drink_info_cart_button);
		bt_add = (LinearLayout)findViewById(R.id.drinks_book_drink_info_add_button);
		bt_share = (LinearLayout)findViewById(R.id.drinks_book_drink_info_share_button);
		bookNum = (EditText)findViewById(R.id.drinks_book_drink_info_hpone_edittext);
		bt_back.setOnClickListener(this);
		bt_cart.setOnClickListener(this);
		bt_add.setOnClickListener(this);
		bt_share.setOnClickListener(this);
		
		expandableListView = (ExpandableListView)findViewById(R.id.drinks_book_drink_info_expendable);
		viewPager = (ViewPager)findViewById(R.id.drinks_book_drink_info_viewpager);
		groupList = new ArrayList<DrinksBookDrinkInfoGroup>();
		eAdapter = new DrinksBookDrinkInfoExpandableListAdapter(ctx, groupList);
		expandableListView.setAdapter(eAdapter);
		expandableListView.setGroupIndicator(null);
		expandableListView.setOnGroupClickListener(new OnGroupClickListener() {
			public boolean onGroupClick(ExpandableListView parent, View v,
					int groupPosition, long id) {
				if(groupPosition == groupList.size()-1) {
					ctx.getIntent().putExtra("typeId", "17");
					ctx.getIntent().putExtra("targetId", crrentDrinks.getId());
					ctx.getIntent().putExtra("commentSucceed", false);
					ctx.setContentView(new CommentWidget(ctx));
				}
				return false;
			}
		});
		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch(msg.what) {
				case MessageWhat.SHOW_DIALOG:
					showMessageDialog(ctx, "正在登陆...");
					break;
				case MessageWhat.DIMISS_DIALOG:
					dismissMessageDialog();
					break;
				case MessageWhat.GETWINEINFO_SUCCEED:
					initWineInfo();
					break;
				case MessageWhat.GETWINEINFO_FAILED:
					initWineInfo();
					break;
				}
			}
			
		};
		initcurrentDrinks();
		initDataPageView();
	}
	public void onClick(View v) {
		switch(v.getId()) {
		case R.id.drink_book_drink_info_back_button:
			if(from != null && from.equals("RecommendHealthWidget")) {
				ctx.setContentView(new RecommendHealthWidget(ctx));
			} else {
				ctx.setContentView(new DrinksBookWidget(ctx));
			}
			break;
		case R.id.drink_book_drink_info_cart_button:
			ctx.setContentView(new DrinksBookCartWidget(ctx));
			break;
		case R.id.drinks_book_drink_info_add_button:
			int num = StringUtils.parseInt(bookNum.getText().toString());
			if(num == 0) {
				showMessage(ctx, "请输入订购数量");
			} else {
				Drinks d = new Drinks();
				d.setId(crrentDrinks.getId());
				d.setName(crrentDrinks.getName());
				d.setImgURL(crrentDrinks.getImgURL());
				d.setPriceTip(crrentDrinks.getPriceTip());
				d.setPriceMarket(crrentDrinks.getPriceMarket());
				d.setNum(num);
				Global.cartList.add(d);
				
				showMessage(ctx, "已放入购物车：" + num);
			}
			break;
		case R.id.drinks_book_drink_info_share_button:

			break;
		default:
			initDrinksInfo(v.getId());
			break;
		}
	}
	private void initDrinksInfo(int id) {
		int num = 0;
		switch(id) {
		case R.id.drinks_book_drink_info_pageview_img1:
			num += 0;
			break;
		case R.id.drinks_book_drink_info_pageview_img2:
			num += 1;
			break;
		case R.id.drinks_book_drink_info_pageview_img3:
			num += 2;
			break;
		case R.id.drinks_book_drink_info_pageview_img4:
			num += 3;
			break;
		case R.id.drinks_book_drink_info_pageview_img5:
			num += 4;
			break;
		case R.id.drinks_book_drink_info_pageview_img6:
			num += 5;
			break;
		}
		int position = crrentPageId*6 + num;
		Drinks drinks = drinksList.get(position);
		if(drinks.isCurrent()) {
			showMessage(ctx, "已是当前酒水详情");
		} else {
			crrentDrinks.setCurrent(false);
			crrentDrinks = drinks;
			crrentDrinks.setCurrent(true);
			
			downLoadData();
		}
	}
	private void initWineInfo() {
		loadImage(iv, crrentDrinks.getImgURL());
		name.setText(crrentDrinks.getName());
		priceTip.setText(crrentDrinks.getPriceTip() +"");
		priceMarket.setText(crrentDrinks.getPriceMarket() + " 元");
		tel.setText(crrentDrinks.getTel());
		ratingBar.setRating(crrentDrinks.getRatings());
		bookNum.setText(1 +"");
		
		groupList.clear();
		group = new DrinksBookDrinkInfoGroup();
		group.setGroupName("酒水介绍");
		childList = new ArrayList<String>();
		childList.add(crrentDrinks.getDesc());
		group.setChildList(childList);
		groupList.add(group);
		
		group = new DrinksBookDrinkInfoGroup();
		group.setGroupName("温馨提示");
		childList = new ArrayList<String>();
		childList.add(crrentDrinks.getPrompt());
		group.setChildList(childList);
		groupList.add(group);
		
		group = new DrinksBookDrinkInfoGroup();
		group.setGroupName("配送说明");
		childList = new ArrayList<String>();
		childList.add(ctx.getResources().getString(R.string.drinks_book_send_explain_info));
		group.setChildList(childList);
		groupList.add(group);
		
		group = new DrinksBookDrinkInfoGroup();
		group.setGroupName("舌尖承诺");
		childList = new ArrayList<String>();
		childList.add(crrentDrinks.getPromise());
		group.setChildList(childList);
		groupList.add(group);
		
		group = new DrinksBookDrinkInfoGroup();
		group.setGroupName("购买评论");
		childList = new ArrayList<String>();
		//childList.add("");
		group.setChildList(childList);
		groupList.add(group);
		
		eAdapter.notifyDataSetChanged();
	}
	private void downLoadData() {
		new Thread() {
			public void run() {
				String response = null;
				try {
					List <NameValuePair> params = new ArrayList <NameValuePair>();
					params.add(new BasicNameValuePair("wineId", crrentDrinks.getId()));
					response = HttpUtils.Post(url, params);
					if(Global.DEBUG) {
						System.out.println("-----------------------------\n" + response);
					}
				} catch(Exception e) {
					Log.e(TAG, "Exception", e);
				}
				if(!StringUtils.isEmpty(response)) {
					JSONManager jManager = new JSONManager();
					boolean isGotJSONObject = jManager.isGotJSONObject(response);
					if(isGotJSONObject) {
						JSONArray jList = jManager.getJsonList();
						if(null == jList) {
							
						} else {
							for(int i=0; i< jList.length(); i++) {
								JSONObject jObject = getJSONObject(jList, i);
								if(null != jObject) {
									crrentDrinks.setPriceMarket(StringUtils.parseFloat(getString(jObject, "marketprice")));
									crrentDrinks.setTel(getString(jObject, "tel"));
									crrentDrinks.setDesc(getString(jObject, "spjs")); //酒水介绍
									crrentDrinks.setPrompt(getString(jObject, "wxgg")); //温馨提示
									crrentDrinks.setPromise(getString(jObject, "sjcn")); //舌尖承诺
								}
							}
						}
						int count = jManager.getResult();
						String msg = jManager.getMsg();
						System.out.println("------ 得到msg: " + count + ":" + msg);
					}
				}
				mHandler.sendEmptyMessage(MessageWhat.GETWINEINFO_SUCCEED);
			}
		}.start();
	}
	private void initcurrentDrinks() {
		if(null != crrentDrinks) {
			loadImage(iv, crrentDrinks.getImgURL());
			name.setText(crrentDrinks.getName());
			priceTip.setText(crrentDrinks.getPriceTip() + "");
			//priceMarket.setText(crrentDrinks.getPriceMarket() + " 元");
			tel.setText(crrentDrinks.getTel());
			ratingBar.setRating(crrentDrinks.getRatings());
		}
	}
	private void initDataPageView() {
		for(Drinks drinks : drinksList) {
			if(drinks.isCurrent()) {
				crrentDrinks = drinks;
				downLoadData();
				break;
			}
		}
		pageViews = new ArrayList<View>();
		int pageCount = drinksList.size()/6 + (drinksList.size()%6 == 0?0:1);
		pageCount = pageCount < 4 ? 4 : pageCount;
		for(int i=0; i< pageCount; i++) {
			pageViews.add(inflater.inflate(R.layout.drinks_book_drinks_info_pageview, null));
		}
		
		Drinks drinks;
		
		for(int i=0; i<pageViews.size(); i++) {
			view = pageViews.get(i);
			iv1 = (ImageView)view.findViewById(R.id.drinks_book_drink_info_pageview_img1);
			iv2 = (ImageView)view.findViewById(R.id.drinks_book_drink_info_pageview_img2);
			iv3 = (ImageView)view.findViewById(R.id.drinks_book_drink_info_pageview_img3);
			iv4 = (ImageView)view.findViewById(R.id.drinks_book_drink_info_pageview_img4);
			iv5 = (ImageView)view.findViewById(R.id.drinks_book_drink_info_pageview_img5);
			iv6 = (ImageView)view.findViewById(R.id.drinks_book_drink_info_pageview_img6);
			int count = drinksList.size() - (i+1)*6;
			if(count >= 0) {
				for(int j=1; j<=6; j++) {
					drinks = drinksList.get(i*6 + j-1);
					initImage(j, drinks);
				}
			} else {
				count = drinksList.size() - i*6;
				for(int j=1; j<=count; j++) {
					drinks = drinksList.get(i*6 + j-1);
					initImage(j, drinks);
				}
				switch(count) {
				case 1:
					iv2.setVisibility(ImageView.INVISIBLE);
					iv3.setVisibility(ImageView.INVISIBLE);
					iv4.setVisibility(ImageView.INVISIBLE);
					iv5.setVisibility(ImageView.INVISIBLE);
					iv6.setVisibility(ImageView.INVISIBLE);
					break;
				case 2:
					iv3.setVisibility(ImageView.INVISIBLE);
					iv4.setVisibility(ImageView.INVISIBLE);
					iv5.setVisibility(ImageView.INVISIBLE);
					iv6.setVisibility(ImageView.INVISIBLE);
					break;
				case 3:
					iv4.setVisibility(ImageView.INVISIBLE);
					iv5.setVisibility(ImageView.INVISIBLE);
					iv6.setVisibility(ImageView.INVISIBLE);
					break;
				case 4:
					iv5.setVisibility(ImageView.INVISIBLE);
					iv6.setVisibility(ImageView.INVISIBLE);
					break;
				case 5:
					iv6.setVisibility(ImageView.INVISIBLE);
					break;
				}
			}
			
		}
		
		pageAdapter = new GeneralPageAdapter(pageViews);
		viewPager.setAdapter(pageAdapter);
		viewPager.setOnPageChangeListener(new GuidePageChangeListener());
	}
	private void initImage(int id, Drinks drinks) {
		switch(id) {
		case 1:
			loadImage(iv1, drinks.getImgURL());
			iv1.setOnClickListener(this);
			break;
		case 2:
			loadImage(iv2, drinks.getImgURL());
			iv2.setOnClickListener(this);
			break;
		case 3:
			loadImage(iv3, drinks.getImgURL());
			iv3.setOnClickListener(this);
			break;
		case 4:
			loadImage(iv4, drinks.getImgURL());
			iv4.setOnClickListener(this);
			break;
		case 5:
			loadImage(iv5, drinks.getImgURL());
			iv5.setOnClickListener(this);
			break;
		case 6:
			loadImage(iv6, drinks.getImgURL());
			iv6.setOnClickListener(this);
			break;
		}
	}
	// 指引页面更改事件监听器
	class GuidePageChangeListener implements OnPageChangeListener {

		public void onPageScrollStateChanged(int arg0) {
		}

		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		public void onPageSelected(int arg0) {
			crrentPageId = arg0;
			switch(arg0) {
			case 0:
				break;
			case 1:
				break;
			case 2:
				break;
			}
		}
	}
	@Override
	public void notifyAdapter() {
		
	}
}
